from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db import models
from app.db.session import get_db
from app.schemas import AlertRuleCreate, AlertRuleUpdate, AlertRuleResponse
from typing import List

router = APIRouter()


@router.post("/rules", response_model=AlertRuleResponse)
def create_alert_rule(rule: AlertRuleCreate, db: Session = Depends(get_db)):
    """创建预警规则"""
    try:
        # 验证任务组是否存在
        task_group = db.query(models.AlertTaskGroup).filter(
            models.AlertTaskGroup.group_name == rule.task_group
        ).first()
        if not task_group:
            raise HTTPException(status_code=400, detail="任务组不存在")

        # 创建规则
        db_rule = models.AlertRule(**rule.dict())
        db.add(db_rule)
        db.commit()
        db.session.refresh(db_rule)
        return db_rule
    except Exception as e:
        db.session.rollback()
        raise HTTPException(status_code=500, detail=f"创建规则失败: {str(e)}")


@router.get("/rules", response_model=List[AlertRuleResponse])
def read_alert_rules(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    rules = db.query(models.AlertRule).offset(skip).limit(limit).all()
    return rules


@router.get("/rules/{rule_id}", response_model=AlertRuleResponse)
def read_alert_rule(rule_id: int, db: Session = Depends(get_db)):
    rule = db.query(models.AlertRule).filter(models.AlertRule.id == rule_id).first()
    if not rule:
        raise HTTPException(status_code=404, detail="Rule not found")
    return rule


@router.put("/rules/{rule_id}", response_model=AlertRuleResponse)
def update_alert_rule(rule_id: int, rule: AlertRuleUpdate, db: Session = Depends(get_db)):
    db_rule = db.query(models.AlertRule).filter(models.AlertRule.id == rule_id).first()
    if not db_rule:
        raise HTTPException(status_code=404, detail="Rule not found")

    for key, value in rule.dict().items():
        setattr(db_rule, key, value)

    db.commit()
    db.refresh(db_rule)
    return db_rule


@router.delete("/rules/{rule_id}")
def delete_alert_rule(rule_id: int, db: Session = Depends(get_db)):
    rule = db.query(models.AlertRule).filter(models.AlertRule.id == rule_id).first()
    if not rule:
        raise HTTPException(status_code=404, detail="Rule not found")

    db.delete(rule)
    db.commit()
    return {"message": "Rule deleted successfully"}